#!/bin/sh
#
# Show unpackaged files in the root filesystem in QDirStat
#
# Author:  Stefan Hundhammer <Stefan.Hundhammer@gmx.de>
# License: GPL V2
#

SCRIPT_NAME=$(basename $0)
SCRIPT_DIR=$(dirname $0)

TMPDIR=/tmp/qdirstat-$USER
ROOT_CACHE=$TMPDIR/root.cache.gz
UNPKG_CACHE=$TMPDIR/root-unpkg.cache.gz
FILELIST=$TMPDIR/filelist.txt

PATH=$SCRIPT_DIR:$PATH


die()
{
    msg="$*"
    echo "$SCRIPT_NAME: FATAL: $msg"
    exit 1
}


create_tmpdir()
{
    test -d $TMPDIR || mkdir -p -m 700 $TMPDIR
    test -d $TMPDIR || die "Can't create tmp dir $TMPDIR"
}


# Make sure the tmp directory has the right user and group ownership and
# permissions

check_tmpdir_security()
{

    test $(stat $TMPDIR --format "%u") -eq $(id -u) || die "$TMPDIR: Wrong user ownership"
    test $(stat $TMPDIR --format "%g") -eq $(id -g) || die "$TMPDIR: Wrong group ownership"
    chmod 700 $TMPDIR
}


create_cache_file()
{
    create_tmpdir
    check_tmpdir_security

    echo -n "Creating QDirStat cache file $ROOT_CACHE ... "

    # Create a normal QDirStat cache file in long format (-l; all paths complete)
    #
    # This needs root permissions to access all files in directories.
    # If "sudo" is not configured for this user, do this step manually.

    sudo qdirstat-cache-writer -l / $ROOT_CACHE
    echo "done."
}


create_complete_filelist()
{
    # This takes a while

    case $(which-pkg-manager) in
        rpm)
            complete-filelist-rpm
            ;;

        dpkg)
            complete-filelist-dpkg
            ;;

        pacman)
            complete-filelist-pacman
            ;;
        *)
            die "No supported package manager found"
            ;;
    esac
}


filter_out_pkg_files_from_cache()
{
    zcat $ROOT_CACHE                             \
        | cache-exclude $FILELIST                \
        | egrep -v '^.\s+/(home|tmp|root|var)/'  \
        | egrep -v '^.\s+/usr/lib/sysimage/rpm/' \
        | cache-kill-empty-dirs                  \
        | gzip                                   \
        >$UNPKG_CACHE
}


show_filtered_cache()
{
    echo "qdirstat -c $UNPKG_CACHE"
    qdirstat -c $UNPKG_CACHE
}


#
# main()
#

# Use -f to force re-reading all information

if [ "$1"x = "-f"x ]; then
    rm -f $ROOT_CACHE
    rm -f $FILELIST
fi

test -f $ROOT_CACHE || create_cache_file
test -f $FILELIST   || create_complete_filelist

filter_out_pkg_files_from_cache
show_filtered_cache

